package com.easyExcel.controller;

import com.alibaba.excel.EasyExcel;
import com.easyExcel.dto.User;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author：万意佳
 * @Date:
 * @Description:
 **/

//*使用EasyExcel操作excel文件上传/下载

@Controller
@RequestMapping(value = "/downExcel")
public class DownloadExcel {

    @RequestMapping("/toExcelPage")
    public String todownloadPage() {
        return "excelPage";
    }

    /**
     * 下载Excel
     * @param request
     * @param response
     */
    @GlobalTransactional
    @RequestMapping(value = "/downloadExcel")
    public void downloadExcel(HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 设置防止中文名乱码
        String filename = URLEncoder.encode("员工信息", "utf-8");
        // 文件下载方式(附件下载还是在当前浏览器打开)
        response.setHeader("Content-disposition", "attachment;filename=" +
                filename + ".xlsx");
        // 构建写入到excel文件的数据
        List<User> user = new ArrayList<>();
        User user1 = new User(1001, "张三", "男", 6666.0, new Date());
        User user2 = new User(1002, "李四", "男", 7777.0, new Date());
        User user3 = new User(1003, "王五", "男", 8888.0, new Date());
        user.add(user1);
        user.add(user2);
        user.add(user3);
        // 写入数据到excel
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                .doWrite(user);
    }
}

